package com.itheima.controller;

import com.itheima.aliyunmessage.SMSUtils;
import com.itheima.code.ValidateCodeUtils;
import com.itheima.entity.Result;
import com.itheima.pub.MessageConstant;
import com.itheima.pub.RedisMessageConstant;
import com.itheima.service.MemberService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("member")
public class MemberController {
    @Autowired
    RedisTemplate redisTemplate;

    @Reference
    MemberService memberService;

    @RequestMapping("sendValidaCode")
    public Result sendValidaCode(@RequestParam("telephone")String telephone){
        try {
            // 随机生成6位验证码(此方法只接受4位或者6位)
            String validateCode = ValidateCodeUtils.generateValidateCode(6);
            // 向指定手机发送生成的验证码
            //SMSUtils.validaCodeSms(telephone,validateCode);
            System.out.println(validateCode);
            // 往redis里添加有时间限制的数据,最后一个参数是单位
            redisTemplate.opsForValue().set(RedisMessageConstant.SENDTYPE_LOGIN+telephone,validateCode,90, TimeUnit.SECONDS);
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    @RequestMapping("login")
    public Result login(@RequestParam("telephone")String telephone,@RequestParam("validaCode")String validaCode){
        try {
            if (validaCode!=null){
                String  redisCode = (String) redisTemplate.opsForValue().get(RedisMessageConstant.SENDTYPE_LOGIN + telephone);
                if (redisCode==null){
                    return new Result(false, "验证码已过期");
                }else {
                    if (validaCode.equals(redisCode)){
                        memberService.addNewMember(telephone);
                        return new Result(true,"登录成功");
                    }else {
                        return new Result(false, "验证码错误");
                    }
                }
            }else {
                return new Result(false, "验证码非法");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, e.getMessage());
        }
    }
}
